/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "StockIndexImage.h"

namespace QSThink
{
	StockMetaInfo::StockMetaInfo(int s,const char* n,int l)
	{
		symbol=s;
		memcpy(name,n,l);
	}

	StockMetaInfo::StockMetaInfo()
	{
		symbol=0;
		memset(name,0,NameMaxLen*sizeof(char));
	}

	void StockMetaInfo::set( int s,const char* n,int l )
	{
		symbol=s;
		memcpy(name,n,l);
	}

	const std::string StockIndexImage::IndexShangHai="ShangHai.index";
	const std::string StockIndexImage::IndexShenZhen="ShenZhen.index";

	//read or write all to disk for simplicity
	StockIndexImage::StockIndexImage(ExchangeType ex) : _exchange(ex),_stockCount(0)
	{

		switch(ex){
			case Exchange_ShangHai:
				_indexFileName=IndexShangHai;
				break;
			case Exchange_ShenZhen:
				_indexFileName=IndexShenZhen;
				break;
		}

		FILE* file=fopen(_indexFileName.c_str(),"rb");//wb+ write file
		if(!file){
			return;
		}

		fseek(file,0L,SEEK_SET);

		fread(&_stockCount,sizeof(_stockCount),1,file);
		fread(_stock,sizeof(StockMetaInfo),_stockCount,file);

		fclose(file);
		//add symbol to map for quick search

		for(int i=0;i<_stockCount;i++){
			_symbolMap.insert(std::map<int,int>::value_type(_stock[i].symbol,i));
		}

	}

	int StockIndexImage::persist(int symbol,const char* name,int nameLen)
	{

		std::map<int,int>::iterator it=_symbolMap.find(symbol);
		if(it!=_symbolMap.end()){
			//find because name is not that easy change just return
			return it->second;
		}

		_stock[_stockCount].set(symbol,name,nameLen);

		_symbolMap.insert(std::map<int,int>::value_type(symbol,_stockCount));


		_stockCount++;

		FILE* file=fopen(_indexFileName.c_str(),"wb");
		fseek(file,0L,SEEK_SET);

		//write stock count
		fwrite(&_stockCount,sizeof(_stockCount),1,file);

		fwrite(_stock,sizeof(StockMetaInfo),_stockCount,file);
		fclose(file);



		return _stockCount-1;
	}

	int StockIndexImage::getSymbolIndex( int symbol )
	{
		std::map<int,int>::iterator it=_symbolMap.find(symbol);
		if(it!=_symbolMap.end()){
			//find because name is not that easy change just return
			return it->second;
		}

		return -1;

	}

	std::string StockIndexImage::getStockName( int symbol )
	{

		std::map<int,int>::iterator it=_symbolMap.find(symbol);
		if(it!=_symbolMap.end()){
			//find because name is not that easy change just return
			int idx=it->second;
			if(_stock[idx].name!=0){
				std::string name(_stock[idx].name);
				return name;
			}


		}

		return "";
		
	}

}
